package com.ruoyi.web.controller.wx;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.core.domain.*;
import com.ruoyi.core.domain.vo.GiftCardVo;
import com.ruoyi.core.service.*;
import com.ruoyi.core.service.impl.WeixinService;
import com.ruoyi.framework.util.ShiroUtils;
import com.ruoyi.system.domain.SysDictData;
import com.ruoyi.system.domain.SysUser;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysDictTypeService;
import com.ruoyi.system.service.ISysUserService;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.apache.shiro.session.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;


import javax.servlet.http.HttpSession;

import java.net.URLEncoder;
import java.nio.channels.SeekableByteChannel;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author lgc
 * @createDate 2020/8/17 - 15:54
 */
@Controller
@RequestMapping("/wx/index")
public class WxViewController extends BaseController {
    private String prefix = "wx";

    @Value("${wechat.redirect}")
    private String redirect;

    @Autowired
    private IUserBannerService userBannerService;
    @Autowired
    private ISysConfigService sysConfigService;
    @Autowired
    private ISysDictTypeService sysDictTypeService;
    @Autowired
    private IProductService productService;
    @Autowired
    private IOrdersService ordersService;
    @Autowired
    private IShopService shopService;
    @Autowired
    private IGiftCardService giftCardService;
    @Autowired
    private WeixinService weixinService;
    @Autowired
    private WxMpService wxMpService;
    @Autowired
    private ISysUserService userService;



    Logger log = LoggerFactory.getLogger(this.getClass());

    /**
     * wx主页
     * @return
     */
    @GetMapping("/{userId}")
    public String au (@PathVariable("userId") String userId)
    {
        //授权回调地址
        String url = "http://redirect/card_v2/wx/index/userInfo"
                .replaceAll("redirect",redirect)
                .replaceAll("/card_v2", ServletUtils.getRequest().getContextPath());
        String redirectURL = wxMpService.oauth2buildAuthorizationUrl(url, WxConsts.OAuth2Scope.SNSAPI_USERINFO, URLEncoder.encode(userId));
        log.info("【微信网页授权】获取code,redirectURL={}", redirectURL);
        return "redirect:" + redirectURL;
    }


    @GetMapping("/userInfo")
    public String userInfo(@RequestParam("code") String code,
                           @RequestParam("state") String returnUrl,
                           HttpSession session) throws Exception {
        log.info("【微信网页授权】code={}", code);
        log.info("【微信网页授权】state={}", returnUrl);
        WxMpOAuth2AccessToken wxMpOAuth2AccessToken;
        try {
            wxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(code);
        } catch (WxErrorException e) {
            log.info("【微信网页授权】{}", e);
            throw new Exception(e.getError().getErrorMsg());
        }
        WxMpUser wxMpUser = wxMpService.oauth2getUserInfo(wxMpOAuth2AccessToken, null);
        WxUserInfo wxUserInfo = weixinService.getWxUserInfo(wxMpService,wxMpUser, returnUrl);
        log.info("【微信用户信息】{}",wxMpUser);

        //存放微信用户
        session.setAttribute(Constants.WX_USER,wxUserInfo);
        //存放用户Id
        session.setAttribute(Constants.USER_ID,returnUrl);
        return "redirect:/wx/index?userId="+returnUrl;
    }



    /**
     * wx主页
     * @param
     * @return
     */
    @GetMapping()
    public String index (ModelMap mmap, HttpSession session)
    {
//        session.setAttribute(Constants.USER_ID,1);
        Long userId = getUserId();
        SysUser sysUser = userService.selectUserById(userId);
        Optional.ofNullable(sysUser).orElseThrow(()->new BusinessException("该用户不存在"));
//        session.setAttribute(Constants.USER_ID,userId);

        String telValue = sysConfigService.selectValueByKeyAndUserId("tel",sysUser.getLoginName());
        mmap.put("telValue",telValue);
        mmap.put("details",sysUser.getDetails());
        return prefix + "/index";
    }


    /**
     * 真伪查询页面
     * @param model
     * @return
     */
    @GetMapping("/fw")
    public String fw(Model model)
    {
        Long userId = getUserId();
        List<UserBanner> bannerList = userBannerService.selectUserBanner(userId);
        model.addAttribute("bannerList",bannerList);
        return prefix + "/fw";
    }

    /**
     * 申请提货验证页面
     * @param model
     * @return
     */
    @GetMapping("/authenticity")
    public String authenticity(Model model)
    {
        Long userId = getUserId();
        SysUser sysUser = userService.selectUserById(userId);
        Optional.ofNullable(sysUser).orElseThrow(()->new BusinessException("该用户不存在"));

        //获取提货规则
//        List<SysDictData> pickupRules = sysDictTypeService.selectDictDataByTypeAndCreateBy("pickup_rules", sysUser.getLoginName());
//        List<String> collect = pickupRules.stream().map(rules -> rules.getDictValue()).collect(Collectors.toList());sysUser
        //获取轮播图
        List<UserBanner> bannerList = userBannerService.selectUserBanner(userId);
        model.addAttribute("bannerList",bannerList);
        model.addAttribute("details",sysUser.getDetails());
        return prefix + "/authenticity";
    }

    /**
     * 产品
     * @param model
     * @return
     */
    @GetMapping("/product")
    public String product(Model model)
    {
        Long userId = getUserId();
        List<Product> products = productService.selectProductAll(userId);
        model.addAttribute("productList",products);
        return prefix + "/product";
    }
    /**
     * 个人中心
     * @param model
     * @return
     */
    @GetMapping("/myself")
    public String myself(HttpSession session,Model model)
    {
        WxUserInfo userInfo =(WxUserInfo)
                Optional.ofNullable(session.getAttribute(Constants.WX_USER))
                        .orElseThrow(()->new BusinessException("请使用微信号授权"));
        model.addAttribute("userInfo",userInfo);
        return prefix + "/myself";
    }

    /**
     * 提货记录
     * @param model
     * @return
     */
    @GetMapping("/myorder")
    public String myorder(HttpSession session,Model model)
    {
        WxUserInfo userInfo =(WxUserInfo)
                Optional.ofNullable(session.getAttribute(Constants.WX_USER))
                        .orElseThrow(()->new BusinessException("请使用微信号授权"));
        Long userId = getUserId();
        Orders orders = new Orders();
        orders.setIsDeleted(0L);
        orders.setCreatedBy(userId);
        //根据微信号获取订单
        orders.setOpenId(userInfo.getOpenId());

        //订单数据
        List<ExpressOrders> list = ordersService.selectExpressOrdersList(orders);
        model.addAttribute("list",list);
        return prefix + "/myorder";
    }

    /**
     * 提货记录
     * @param model
     * @return
     */
    @GetMapping("/record")
    public String record(HttpSession session,Model model)
    {
        WxUserInfo userInfo =(WxUserInfo)
                Optional.ofNullable(session.getAttribute(Constants.WX_USER))
                        .orElseThrow(()->new BusinessException("请使用微信号授权"));
        Long userId = getUserId();
        Orders orders = new Orders();
        orders.setIsDeleted(0L);
        orders.setCreatedBy(userId);
        //根据微信号获取订单
        orders.setOpenId(userInfo.getOpenId());

        //订单数据
        List<ExpressOrders> list = ordersService.selectExpressOrdersList(orders);
        model.addAttribute("list",list);
        return prefix + "/record";
    }

    /**
     * 礼品详情
     * @return
     */
    @GetMapping("/goodDetail/{cardId}")
    public String goodDetail(@PathVariable("cardId") Long cardId,Model model)
    {
        Long userId = getUserId();
        GiftCard giftCard = giftCardService.selectGiftCardById(cardId);
        Product product = productService.selectProductById(giftCard.getProductId().longValue());

        model.addAttribute("product",product);
        model.addAttribute("cardId",cardId);
        model.addAttribute("destails",userService.selectUserById(userId).getDetails());
        return prefix + "/goodsDetail";
    }

    /**
     * 申请提货
     * @return
     */
    @GetMapping("/apply/{cardId}")
    public String apply(@PathVariable("cardId") Long cardId, Model model, HttpSession session)
    {
        StringBuilder sb = new StringBuilder(20);
        sb.append(Constants.CARDID_CODE).append(":").append(cardId);
        Optional.ofNullable(session.getAttribute(sb.toString()))
                .orElseThrow(()->new BusinessException("请进行码验证！"));


        Long userId = getUserId();
        GiftCard giftCard = new GiftCard();giftCard.setGiftCardId(cardId);
        List<GiftCardVo> giftCardVos = giftCardService.selectGiftCardList(giftCard);
        List<Shop> shopList = shopService.selectShopAll(userId);
        model.addAttribute("shopList",shopList);
        if (!giftCardVos.isEmpty()){
            model.addAttribute("giftCard",giftCardVos.get(0));
        }
        return prefix + "/apply";
    }


    /**
     * 地图
     * @return
     */
    @GetMapping("/map")
    public String map(Long shopId,Model model)
    {
        Shop shop = shopService.selectShopById(shopId);
        model.addAttribute("shop",shop);
        return prefix + "/map";
    }


    /**
     * 更新取货点
     * @return
     */
    @GetMapping("/update")
    public String update(Long shopId,Long giftCardId,Model model)
    {
        Shop shop = shopService.selectShopById(shopId);
        model.addAttribute("shop",shop);
        model.addAttribute("giftCardId",giftCardId);
        return prefix + "/update";
    }

    /**
     * 申请提货
     * @return
     */
    @GetMapping("/perfect")
    public String perfect(Long shopId,Long giftCardId,Model model,HttpSession session)
    {
        StringBuilder sb = new StringBuilder(20);
        sb.append(Constants.CARDID_CODE).append(":").append(giftCardId);
        Optional.ofNullable(session.getAttribute(sb.toString()))
                .orElseThrow(()->new BusinessException("请进行码验证！"));

        GiftCard giftCard = new GiftCard();giftCard.setGiftCardId(giftCardId);
        List<GiftCardVo> giftCardVos = giftCardService.selectGiftCardList(giftCard);
        Shop shop = shopService.selectShopById(shopId);
        if (!giftCardVos.isEmpty()){
            model.addAttribute("giftCard",giftCardVos.get(0));
        }
        model.addAttribute("shop",shop);
        return prefix + "/perfect";
    }


    /**
     * 申请自提成功页面
     * @return
     */
    @GetMapping("/ok/{orderId}")
    public String ok(@PathVariable("orderId")Long orderId, Model model)
    {
        Orders orders = ordersService.selectOrdersById(orderId.toString());
        GiftCard giftCard = new GiftCard();giftCard.setGiftCardId(orders.getGiftCardId());
        List<GiftCardVo> giftCardVos = giftCardService.selectGiftCardList(giftCard);
        if (!giftCardVos.isEmpty()){
            model.addAttribute("giftCard",giftCardVos.get(0));
        }
        Shop shop = shopService.selectShopById(orders.getShopId());
        model.addAttribute("shop",shop);
        model.addAttribute("orders",orders);
        return prefix + "/ok";
    }
    /**
     * 申请发货成功页面
     * @return
     */
    @GetMapping("/success/{orderId}")
    public String success(@PathVariable("orderId")Long orderId, Model model)
    {
        Orders orders = ordersService.selectOrdersById(orderId.toString());
        GiftCard giftCard = new GiftCard();giftCard.setGiftCardId(orders.getGiftCardId());
        List<GiftCardVo> giftCardVos = giftCardService.selectGiftCardList(giftCard);
        if (!giftCardVos.isEmpty()){
            model.addAttribute("giftCard",giftCardVos.get(0));
        }
        model.addAttribute("orders",orders);
        return prefix + "/success";
    }


}
